// 2013-9-26下午01:31:45  net.betou.trade.admin.action.SharesAct.java

package net.betou.trade.admin.action;

import static net.betou.common.page.SimplePage.cpn;
import static net.betou.common.page.SimplePage.cpnPageSize;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.betou.common.util.TradeUtils;
import net.betou.common.web.springmvc.WebApplicationUtils;
import net.betou.trade.action.abs.ActionSupport;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.entity.main.Role;
import net.betou.trade.entity.main.Share;
import net.betou.trade.share.Template;
import net.betou.trade.web.Messages;
import net.betou.trade.web.WebErrors;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 
 * @author 叶装装
 */
@Controller
public class SharesAct extends ActionSupport< Share >{
	
	private static final String BEAN_SUFFIX = "Share";
	
	@RequestMapping( "/share/v_list.jspx" )
	public String list( String view,  Integer pageSize, Integer pageNo, String searchProperty, String searchValue, String orderProperty, String orderDirection, String filterStatus, HttpServletRequest request, HttpServletResponse response, ModelMap model ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		WebErrors errors = validate( admin, view );
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		pageSize = cpnPageSize( pageSize );
		pageNo = cpn( pageNo );
		
		Template template = getTemplate( view + BEAN_SUFFIX );
		
		template.setPage( model, admin, pageSize, pageNo, searchProperty, searchValue, orderProperty, orderDirection, filterStatus );
		template.afterPage( model );
		
		
		model.addAttribute( "view", view );
		model.addAttribute( "admin", admin );
		
		return  SharingSettingsAct.DIRECTORY + "/" +  view + "_list";
		
	}
	
	private Template getTemplate( String beanName ){
		return ( Template ) applicationUtils.getBean( beanName );
	}
	
	private WebErrors validate( AgentAndAdmins admin, String config ){
		
		WebErrors errors = WebErrors.create( );
		
		if( StringUtils.isBlank( config ) || !hasPerm ( admin, "config_" + config )){
			errors.addError( Messages._403 );
		}
		
		return errors;
	}
	
	private boolean hasPerm( AgentAndAdmins admin, String config ){
		Role role = admin.getSearchSettingRole( );
		if( role == null ){
			return false;
		}
		
		Set< String > shares = role.getShares( );
		
		if( shares == null || shares.isEmpty( ) ){
			return false;
		}
		
		return shares.contains( config );
	}
	
	@Override
	protected String getDirectory( ) {
		return null;
	}
	
	@Autowired
	private WebApplicationUtils applicationUtils;
}
